package com.jack.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.jack.model.ProductCategory;
import com.jack.model.ProductInfo;
import com.jack.service.CategoryService;
import com.jack.service.ProductInfoService;
import com.jack.vo.ProductInfoVo;
import com.jack.vo.ProductVo;
import com.jack.vo.ResultVo;


@RestController
@RequestMapping("/buyer/product")
public class BuyerProductController {

	@Autowired
	private ProductInfoService productInfoService;

	@Autowired
	private CategoryService categoryService;

	@GetMapping("/list")
	public ResultVo list() {
		// 1. query all up productInfo
		List<ProductInfo> ProductInfoList = productInfoService.findUpAll();
		// 2. query product category
		List<Integer> categoryTypeList = ProductInfoList.stream().map(e -> e.getCategoryType()).collect(Collectors.toList());
		List<ProductCategory> ProductCategoryList = categoryService.findByCategoryTypeIn(categoryTypeList);
		// 3. aggragate all data
		
		List<ProductVo> productVoList = new ArrayList<ProductVo>();
		for (ProductCategory productCategory : ProductCategoryList) {
			ProductVo productVo = new ProductVo();
			productVo.setName(productCategory.getCategoryName()	);
			productVo.setType(productCategory.getCategoryType());
			List<ProductInfoVo> productInfoVoList = new ArrayList<ProductInfoVo>();
			for (ProductInfo productInfo : ProductInfoList) {
				if(productCategory.getCategoryType().equals(productInfo.getCategoryType())) {
					ProductInfoVo productInfoVo = new ProductInfoVo();
					BeanUtils.copyProperties(productInfo, productInfoVo);
					productInfoVoList.add(productInfoVo);
				}
					
				
			}
			productVo.setProductInfoVo(productInfoVoList);
			productVoList.add(productVo);
		}
		
		ResultVo vo = new ResultVo();
		vo.setData(productVoList);
		vo.setCode(0);
		vo.setMsg("成功");

		return vo;
	}
}
